/**
 * 
 */
package org.myontology.controller.impl;

import java.util.Iterator;
import java.util.List;

import model.Vocabulary;

import org.apache.log4j.Logger;
import org.myontology.controller.AbstractAction;
import org.myontology.controller.Action;
import org.myontology.controller.AttributeHolder;
import org.myontology.controller.AttributeLevel;
import org.myontology.controller.SesameSession;
import org.myontology.controller.ValueHandler;
import org.myontology.controller.rules.SimpleRuleEngine;
import org.myontology.logging.ElementLogging;
import org.openrdf.model.URI;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.model.vocabulary.RDF;

/**
 *  @author <a href="michael.hackl@sti2.at">Michael Hackl</a>
 * Project: Myontology - www.myontology.org
 * STI
 */
public class DeleteOMAction extends AbstractAction implements Action {

	private SimpleRuleEngine rules;
	private SesameSession session;
	private Logger logger;
	
	private ElementLogging elementLogging;
	
	public static final ValueHandler<URI> URI = new ValueHandler<URI>(AttributeLevel.SESSION,DeleteOMAction.class);
	public static final ValueHandler<List<String>> DELETEABLES = new ValueHandler<List<String>>(AttributeLevel.REQUEST,DeleteOMAction.class);

	
	/* (non-Javadoc)
	 * @see org.myontology.controller.Action#execute(org.myontology.controller.AttributeHolder)
	 */
	public void execute(AttributeHolder attributes) throws Exception {
		String uri=attributes.getRequestParameter("deleteURI");
		if (uri!=null) {
			URI ontURI = new URIImpl(Vocabulary.ONTOLOGYMODULE_NAMESPACE+uri);
			deleteRecursive(ontURI,attributes);
			
		}
			List<String> oms =session.loadSubjectsByObject(RDF.TYPE, Vocabulary.ONTOLOGYMODULE);
			for (Iterator<String> it = oms.iterator();it.hasNext(); ) {
				if (session.hasTriple(new URIImpl(it.next()), Vocabulary.ISLOCKED, null)) {
					it.remove();
				}
			}
			DELETEABLES.setValue(attributes, oms);
		
	}


	/**
	 * @param ontURI
	 * @throws Exception
	 */
	private void deleteRecursive(URI ontURI,AttributeHolder attributes) throws Exception {
		elementLogging.logDelete(ontURI, attributes);
		List<String> related = session.loadSubjectsByObject(null, ontURI);
		for (Iterator<String> it = related.iterator();it.hasNext();) {
			URI uri = new URIImpl(it.next());
			deleteRecursive(uri,attributes);
		}
		logger.info("delete "+ontURI);
		session.remove(ontURI, null, null);
	}

}
